#include "mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

MYFILE *myfopen(const char *filepath, const char *way)
{
	int file_id;
	if(strcmp(way, "w") == 0)
		file_id = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0666);
	else if(strcmp(way, "a") == 0)
		file_id = open(filepath, O_WRONLY | O_CREAT | O_APPEND, 0666);
	else if(strcmp(way, "r") == 0)
		file_id = open(filepath, O_RDONLY);
	else
		return NULL;

	MYFILE *ret = (MYFILE*)malloc(sizeof(MYFILE));
	if(!ret)
		return NULL;
	ret->inode = file_id;
	ret->OpenWay = way;
	ret->buffer = (char*)malloc(BUFSIZE * sizeof(char));
	ret->buflen = 0;

	return ret;
}

void myclose(MYFILE *file)
{
	if(file->inode < 0)
		return;
	myfflush(file);
	close(file->inode);
	free(file->buffer);
	free(file);
}


int mywrite(MYFILE *file, void *str, int len)
{
	int ret = 0;
	while(len--)
	{
		*(file->buffer + file->buflen) = *((char*)str + ret);
		
		if(*(file->buffer + file->buflen)  == '\n' || file->buflen == BUFSIZE)
			myfflush(file);
		else
			++file->buflen;
		++ret;
	}
	return ret;
}

void myfflush(MYFILE *file)
{
	if(file->buflen < 0)
		return;

	write(file->inode, file->buffer, file->buflen);
	fsync(file->inode);
	file->buflen = 0;
	
}
